package com.iqismart.shorturl.config;

import com.iqismart.shorturl.utils.UserTokenUtils;

/**
 * @Description
 * @Auther sty
 * @createTime 2019/10/14 01:51
 */
public class UidHolder {
    private static final ThreadLocal<Long> contextHolder = new ThreadLocal();
    private static final ThreadLocal<String> contextAccountHolder = new ThreadLocal();

    public UidHolder() {
    }

    public static void setUid(Long uid) {
        contextHolder.set(uid);
    }

    public static void setAccount(String account) {
        contextAccountHolder.set(account);
    }

    public static Long getUid() {
        Long uid = null;
        try {
            uid = (Long)contextHolder.get();
            uid = UserTokenUtils.getUID();
        } catch (Exception e) {
            return 0L;
        }

        return uid;
    }

    public static Long mustUid() {
        Long uid = null;
        uid = (Long)contextHolder.get();
        if (uid == null || uid == 0L) {
            uid = UserTokenUtils.getUID();
            setUid(uid);
        }
        return uid;
    }

    public static String getAccount() {
        String account = (String)contextAccountHolder.get();
        return account == null ? "" + getUid() : account;
    }

    public static void clear() {
    }

    public static boolean compare(Long uid) {
        if (uid != null && uid != 0L) {
            if (getUid() != null && getUid() != 0L) {
                return uid.equals(getUid());
            } else {
                throw new RuntimeException("token解析错误");
            }
        } else {
            return false;
        }
    }
}